<template>
    <div class="app-manage-dialog-modal-wrapper">
        <el-dialog :model-value="props.value" :title="dialog.title" :width="dialog.width" destroy-on-close>
            <el-form ref="ruleFormRef" :model="formData" :rules="ruleForm" label-width="120px">
                <div class="form-item-box-one">
                    <div>
                        <el-form-item label="应用名称" prop="appName">
                            <el-input
                                v-model="formData.appName"
                                @input="value => (formData.appName = value.trim())"
                                placeholder="请输入应用名称"
                                :disabled="props.readonly"
                                maxlength="50"
                            />
                        </el-form-item>
                        <el-form-item label="状态" prop="status">
                            <el-radio-group v-model="formData.status" :disabled="props.readonly">
                                <el-radio
                                    v-for="(value, key) in sys_normal_disable"
                                    :label="value.label"
                                    :key="key"
                                    :value="value.value"
                                ></el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>
                    <div>
                        <el-form-item label="标识符" prop="appCode">
                            <el-input
                                v-model="formData.appCode"
                                @input="value => (formData.appCode = value.trim())"
                                placeholder="请输入标识符"
                                :disabled="isEdit() || props.readonly"
                                maxlength="50"
                            />
                        </el-form-item>
                        <el-form-item label="显示顺序">
                            <el-input-number
                                v-model="formData.seq"
                                :precision="0"
                                :min="1"
                                style="width: 100%"
                                align="left"
                                controls-position="right"
                                placeholder="请输入显示顺序"
                                :disabled="props.readonly"
                            />
                        </el-form-item>
                    </div>
                </div>
                <el-form-item label="地址" prop="address">
                    <el-input
                        v-model="formData.address"
                        maxlength="200"
                        show-word-limit
                        placeholder="请输入地址"
                        :disabled="props.readonly"
                    />
                </el-form-item>
                <el-form-item label="描述" prop="remark">
                    <el-input
                        v-model="formData.remark"
                        maxlength="200"
                        show-word-limit
                        type="textarea"
                        placeholder="请输入描述"
                        :disabled="props.readonly"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="props.close">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import type { AppVO } from '@great/services';
import { systemAppService } from '@great/services';
import { reactive, ref } from 'vue';
import type { PopupBoxProps } from '@great/utils';
import { useRequest } from 'vue-request';

const { proxy } = getCurrentInstance() as any;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

interface IProps extends PopupBoxProps {
    row?: AppVO;
    getList?: () => Promise<void>;
    readonly?: boolean;
}
const props = defineProps<IProps>();

interface Dialog {
    title: string;
    width: number;
    detail?: AppVO;
}
const dialog = reactive<Dialog>({
    title: '新建应用',
    width: 900,
    detail: undefined
});

const formData = reactive<AppVO>({
    appName: '', // 应用名称
    appCode: '', // 标识符
    status: '0', // 状态
    seq: undefined, // 显示顺序
    remark: '', // 描述
    address: '' // 地址
});

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<FormRules>({
    appName: [{ required: true, message: '请输入应用名称', trigger: ['blur', 'change'] }],
    appCode: [
        { required: true, message: '请输入标识符', trigger: ['blur', 'change'] },
        {
            validator: (rule, value, callback) => {
                // 大写字母开头
                if (!/^[A-Z]/.test(value)) {
                    return callback(new Error('必须以大写字母开头'));
                }
                // 字母数字组合且符合驼峰命名
                if (!/^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]+)*$/.test(value)) {
                    return callback(new Error('必须是字母数字组合且符合驼峰命名法'));
                }
                callback();
            },
            trigger: ['blur', 'change']
        }
    ],
    status: [{ required: true, message: '请选择状态', trigger: ['blur', 'change'] }]
});

// 是否为编辑
const isEdit = (par?: boolean): boolean => {
    if (par === undefined) {
        return dialog.title.includes('修改');
    } else {
        return dialog.title.includes('修改') && par;
    }
};

// 提交接口请求
const { run, loading } = useRequest(
    () => {
        return systemAppService[isEdit() ? 'updateApp' : 'addApp'](formData);
    },
    {
        manual: true,
        onSuccess(res) {
            ElNotification({
                title: isEdit() ? '修改成功！' : '创建成功！',
                type: 'success'
            });
            closeDialog();
        }
    }
);
// 表单提交
const submitForm = () => {
    if (props.readonly) {
        closeDialog();
        return;
    }
    ruleFormRef.value?.validate(valid => {
        valid && run();
    });
};

//关闭弹框
const closeDialog = () => {
    props.close();
    if (props.getList) props.getList();
};

// 打开弹框
const openDialog = () => {
    if (props.row) {
        if (props.readonly) {
            dialog.title = '查看应用';
        } else {
            dialog.title = '修改应用';
        }
        dialog.detail = JSON.parse(JSON.stringify(props.row));
        formData.appId = props.row.appId;
        Object.keys(formData).forEach(key => {
            formData[key] = (props.row as AppVO)[key];
        });
    }
};

const init = () => {
    openDialog();
};
init();
</script>
<style scoped lang="scss">
.app-manage-dialog-modal-wrapper {
    .el-form {
        .form-item-box-one {
            display: flex;
            justify-content: space-between;
            > div {
                width: calc((100% - 10px) / 2);
            }
        }
    }
}
</style>
